//
//  WebViewVC.m
//  LuQu
//
//  Created by xp on 2017/7/25.
//  Copyright © 2017年 mingthink. All rights reserved.
//

#import "WebViewVC.h"
#import <JavaScriptCore/JavaScriptCore.h>
#import "JSObjectModel.h"
#import "QRCodeReaderViewController.h"
#import "CorePhotoPickerVCManager.h"
@interface WebViewVC ()<UIWebViewDelegate,JavaScriptObjectiveCDelegate,UIActionSheetDelegate>
{
    JSObjectModel *model;
    UIWebView *mainWebV;
}
@property (nonatomic, strong) JSContext *jsContext;
@end

@implementation WebViewVC

- (void)viewDidLoad {
    [super viewDidLoad];
    if ([StringUtils isEmpty:_urlStr]) {
        _urlStr=@"devhybrid.91luqu.cn";
    }
    [self setWebCookie];
    [self initWebView];
}
-(void)initWebView
{
    mainWebV=[[UIWebView alloc]initWithFrame:CGRectMake(0, NAVBAR_HEIGH, DEVW, DEVH-NAVBAR_HEIGH-TABBAR_HEIGH)];
    [self.view addSubview:mainWebV];
    mainWebV.delegate=self;
    NSURL *url=[NSURL URLWithString:_urlStr];
    
     //NSURL *url = [[NSBundle mainBundle] URLForResource:@"abc" withExtension:@"html"];
    
    NSMutableURLRequest *request=[NSMutableURLRequest requestWithURL:url];
//    [request setHTTPShouldHandleCookies:YES];
//    [request setValue:[NSString stringWithFormat:@"%@=%@",@"token", @"2222222"] forHTTPHeaderField:@"Cookie"];

    [mainWebV loadRequest:request];
    
}
-(void)setWebCookie{
    AppDelegate *app = (AppDelegate *)[[UIApplication sharedApplication] delegate];
    NSArray *tempArray=@[@[@"token",app.loginMember.AccessToken],@[@"fromtype",@"1"],@[@"osver",[MyUtility getAppShortVersion]]];
    NSURL *url=[NSURL URLWithString:_urlStr];
    //NSString *domainStr=[NSString stringWithFormat:@"%@://%@",url.scheme,url.host];
    for (NSArray *array in tempArray) {
        NSMutableDictionary *cookieProperties = [NSMutableDictionary dictionary];
        [cookieProperties setObject:array[0] forKey:NSHTTPCookieName];
        [cookieProperties setObject:array[1]forKey:NSHTTPCookieValue];
        [cookieProperties setObject:url.host forKey:NSHTTPCookieDomain];
        //[cookieProperties setObject:_urlStr forKey:NSHTTPCookieOriginURL];
        [cookieProperties setObject:@"/" forKey:NSHTTPCookiePath];
        [cookieProperties setObject:@"0" forKey:NSHTTPCookieVersion];
        [cookieProperties setObject:[NSDate dateWithTimeIntervalSinceNow:60*60] forKey:NSHTTPCookieExpires];//设置失效时间
        [cookieProperties setObject:@"0" forKey:NSHTTPCookieDiscard]; //设置sessionOnly
        NSHTTPCookie *cookie = [NSHTTPCookie cookieWithProperties:cookieProperties];
        [[NSHTTPCookieStorage sharedHTTPCookieStorage] setCookie:cookie];
    }
    
}

#pragma mark - UIWebViewDelegate
- (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType {
    DeLog(@"------request:%@",request.URL);
    return YES;
}
- (void)webViewDidStartLoad:(UIWebView *)webView{
    
}

- (void)webViewDidFinishLoad:(UIWebView *)webView {
    
   NSArray *cookies = [[NSHTTPCookieStorage sharedHTTPCookieStorage] cookies];
    DeLog(@"-----cookie2:%@",cookies);
    
    NSString *agent2 = [webView stringByEvaluatingJavaScriptFromString:@"navigator.userAgent"];
    DeLog(@"-----agent2:%@",agent2);
    JSContext *context = [webView valueForKeyPath:@"documentView.webView.mainFrame.javaScriptContext"];
    // 通过模型调用方法，这种方式更好些。
    model  = [[JSObjectModel alloc] init];
    context[@"MtJsBridge"] = model;
    model.jsContext=context;
    model.delegate = self;
    
    context.exceptionHandler = ^(JSContext *context, JSValue *exceptionValue) {
        context.exception = exceptionValue;
        NSLog(@"异常信息：%@", exceptionValue);
    };
}
- (void)webView:(UIWebView *)webView didFailLoadWithError:(NSError *)error{
    
}
-(void)jsShowToast:(id)json{
     DeLog(@"------json1:%@",json);
     DeLog(@"------json2:%@",json[@"text"]);
    [WToast showWithText:json[@"text"]];
    JSValue *jsFunc = model.jsContext[@"success"];
    [jsFunc callWithArguments:nil];
}
-(void)jsChooseImage{
    UIActionSheet *sheet = [[UIActionSheet alloc]initWithTitle:nil delegate:self cancelButtonTitle:@"取消" destructiveButtonTitle:@"相册" otherButtonTitles:@"拍照", nil];
    [sheet showInView:self.view];
}
-(void)jsShowPageLoading:(id)json{
    DeLog(@"------json:%@",json);
//    [SVProgressHUD setDefaultMaskType:SVProgressHUDMaskTypeNone];//背景不能点击
//    [SVProgressHUD setDefaultStyle:SVProgressHUDStyleDark];
//    [SVProgressHUD setCornerRadius:6];
//    [SVProgressHUD setDefaultAnimationType:SVProgressHUDAnimationTypeFlat];//圆圈图形
//    [SVProgressHUD showWithStatus:json[@"title"]];

    JSContext *context=[JSContext currentContext];
    JSValue *jsFunc = model.jsContext[json[@"success"]];
    
    NSString *str=[@{@"title":@"aaaaa"}mj_JSONString];
    [jsFunc callWithArguments:@[str]];
}

-(void)jsClosePageLoading{
     [SVProgressHUD dismiss];
    JSValue *jsFunc = model.jsContext[@"success"];
    [jsFunc callWithArguments:nil];
}
-(void)jsShowShareMenu{
    
}

-(void)jsGetLocation{
    
}
-(void)jsWXPay{
    
}
-(void)jsScanQRCode{
    QRCodeReaderViewController *reader = [QRCodeReaderViewController new];
    reader.modalPresentationStyle = UIModalPresentationFormSheet;
    //reader.delegate = self;
    
    WEAK_SELF(self);
    [reader setCompletionWithBlock:^(NSString *resultAsString) {
        [EMAlertView showAlertWithTitle:nil message:resultAsString completionBlock:^(NSUInteger buttonIndex, EMAlertView *alertView) {
            [weakSelf.navigationController popViewControllerAnimated:YES];
        }
                      cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
        
    }];
    [self.navigationController pushViewController:reader animated:YES];
    JSValue *jsFunc = model.jsContext[@"success"];
    [jsFunc callWithArguments:nil];
}
-(void)jsCheckNetworkStatus{
    
}
-(void)jsUserLogin{
    AppDelegate *appDel = (AppDelegate *)[[UIApplication sharedApplication] delegate];
        [appDel goLogin];
    JSValue *jsFunc = model.jsContext[@"success"];
    [jsFunc callWithArguments:nil];
}
-(void)jsWXLogin{
    
}
- (void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex {
    [self clickAlertActionWithIndex:buttonIndex];
}
- (void)clickAlertActionWithIndex:(NSInteger)index {
    CorePhotoPickerVCMangerType type = 0;
    if(index == 0) {
        type = CorePhotoPickerVCMangerTypeSinglePhoto;
    }
    else if(index == 1) {
        type = CorePhotoPickerVCMangerTypeCamera;
    }
    else if(index > 1) {
        //取消图片选择
        return;
    }
    
    CorePhotoPickerVCManager *manager = [CorePhotoPickerVCManager sharedCorePhotoPickerVCManager];
    //设置类型
    manager.pickerVCManagerType = type;
    //最多可选1张
    manager.maxSelectedPhotoNumber = 1;
    //错误处理
    if(manager.unavailableType != CorePhotoPickerUnavailableTypeNone){
        DeLog(@"设备不可用");
        NSString *strMsg = @"设备不可用";
        [self.view makeToast:strMsg];
        return;
    }
    
    UIViewController *pickerVC = manager.imagePickerController;
    //选取结束
    manager.finishPickingMedia=^(NSArray *medias){
        DeLog(@"medias.count=%lu",(unsigned long)medias.count);
        [medias enumerateObjectsUsingBlock:^(CorePhoto *photo, NSUInteger idx, BOOL *stop) {
            DeLog(@"%@",photo.editedImage);
            NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask, YES);
            NSString *filePath = [[paths objectAtIndex:0] stringByAppendingPathComponent:[NSString stringWithFormat:@"pic_100.png"]];   // 保存
            [UIImagePNGRepresentation(photo.editedImage)writeToFile: filePath    atomically:YES];
            JSValue *jsFunc = model.jsContext[@"onImageUploaded"];
            NSArray *params=@[filePath,filePath,filePath];
            [jsFunc callWithArguments:params];
            //            img_background.image = photo.editedImage;
        }];
    };
    [self presentViewController:pickerVC animated:YES completion:nil];
}
- (void)checkNetWorkConnectStatus {
    // 1.获得网络监控的管理者
    AFNetworkReachabilityManager *manager = [AFNetworkReachabilityManager sharedManager];
    // 2.设置网络状态改变后的处理
    [manager setReachabilityStatusChangeBlock:^(AFNetworkReachabilityStatus status) {
        // 当网络状态改变了, 就会调用这个block
        switch (status) {
            case AFNetworkReachabilityStatusUnknown: // 未知网络
                DeLog(@"未知网络");
                break;
            case AFNetworkReachabilityStatusNotReachable: // 没有网络(断网)
                [WToast showWithText:@"网络连接失败，请检查网络"];
                //NSLog(@"没有网络(断网)");
                break;
            case AFNetworkReachabilityStatusReachableViaWWAN: // 手机自带网络
                NSLog(@"手机自带网络");
                break;
            case AFNetworkReachabilityStatusReachableViaWiFi: // WIFI
                DeLog(@"WIFI");
                break;
        }
    }];
    // 3.开始监控
    [manager startMonitoring];
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}


@end
